package com.uenpay.im.ui.old.activity.contacts;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qyx.android.database.FriendDB;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.utils.QyxWeightDensityUtils;
import com.qyx.android.weight.view.MyListView;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.group.ChooseGroupMemberAdapter;
import com.uenpay.im.ui.old.activity.group.MyGroupsActivity;
import com.uenpay.im.ui.old.activity.label.CreateLabelActivity;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.configuration.QYXIMConfiguration;
import com.uenpay.im.entities.SelectedFriendEntity;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;
import java.util.Locale;

/**
 * @author SL
 * @created 2015-12-28 下午1:43:08
 * @copyRight http://www.qiyunxin.com
 * @function 群聊加人、创建群聊、标签添加人，选择联系人列表
 */
public class ChooseContactsActivity extends BaseActivity {
    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout selectedUserLayout;

    private ChooseGroupMemberAdapter chooseGroupMemberAdapter = null;
    private ArrayList<SelectedFriendEntity> selectedMembers = new ArrayList<SelectedFriendEntity>();
    private ArrayList<SelectedFriendEntity> selectedFriendEntities = new ArrayList<SelectedFriendEntity>();
    private ArrayList<FriendEntity> arraylist = null;
    private MyListView pinnedListView;
    private TextView rightTextView, choose_group_tv;
    private EditText search_et;
    private ArrayList<FriendEntity> friends;
    private String cust_id = "";
    private FriendEntity friend;
    private boolean isAddLabel = false;
    // 聊天发送名片
    private boolean isChooseCrad = false;
    private View loading;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_delete_group_member_layout;
    }

    @Override
    public void initView(View view) {
        if (getIntent() != null) {

            if (getIntent().hasExtra("talkId")) {
                cust_id = getIntent().getStringExtra("talkId");
                friend = FriendDB.getFriend(cust_id);
            }

            if (getIntent().hasExtra("isAddLabel")) {
                isAddLabel = getIntent().getBooleanExtra("isAddLabel", false);
            }

            if (getIntent().hasExtra("isChooseCrad")) {
                isChooseCrad = getIntent().getBooleanExtra("isChooseCrad",
                        false);
            }
            if (getIntent().hasExtra("arraylist")) {

                arraylist = (ArrayList<FriendEntity>) getIntent()
                        .getSerializableExtra("arraylist");
            }
        }

        initView();
        initListener();
        refresh();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.add_group_member));
        rightTextView = ((TextView) findViewById(R.id.title_right_tv));
        rightTextView.setText(getResources().getString(R.string.sure));
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.selected_users_scroll);
        selectedUserLayout = (LinearLayout) findViewById(R.id.selected_users);
        pinnedListView = (MyListView) findViewById(R.id.pinnedListView);
        choose_group_tv = (TextView) findViewById(R.id.choose_group_tv);
        search_et = (EditText) findViewById(R.id.search_et);
        loading = findViewById(R.id.loading);

        if (isAddLabel || isChooseCrad) {
            choose_group_tv.setVisibility(View.GONE);
            findViewById(R.id.choose_group_view).setVisibility(View.GONE);
            if (isChooseCrad) {
                ((TextView) findViewById(R.id.title_textview))
                        .setText(getResources().getString(
                                R.string.choose_friends_to_chat));
                findViewById(R.id.title_right_layout).setVisibility(View.GONE);
            }
        }
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        finish();
                    }
                });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (selectedMembers == null
                                || selectedMembers.size() <= 0) {
                            IMApplication.showToast(getResources().getString(
                                    R.string.list_is_empty));
                            return;
                        }
                        findViewById(R.id.title_right_layout).setEnabled(false);
                        if (isAddLabel) {
                            labelChooseMembers();
                        }
                    }
                });

        pinnedListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        SelectedFriendEntity selected = (SelectedFriendEntity) arg0
                                .getAdapter().getItem(arg2);
                        if (selected != null) {
                            if (isChooseCrad) {
                                Intent intent = new Intent();
                                intent.putExtra("selectedUser", selected.friend);
                                setResult(RESULT_OK, intent);
                                finish();
                                return;
                            }
                        }
                        if (selected.selectedStatus == 3)
                            return;
                        for (int i = 0; i < selectedFriendEntities.size(); i++) {
                            if (selectedFriendEntities.get(i).friend.cust_id
                                    .equals(selected.friend.cust_id)) {
                                if (selectedFriendEntities.get(i).selectedStatus == 1) {
                                    selectedFriendEntities.get(i).selectedStatus = 2;
                                } else {
                                    selectedFriendEntities.get(i).selectedStatus = 1;
                                }
                                break;
                            }
                        }
                        chooseGroupMemberAdapter.notifyDataSetChanged();
                        if (chooseGroupMemberAdapter
                                .isSelected(selected.friend.cust_id) == 2) {
                            selectedMembers.add(selected);
                            addSelectedFriend(selected.friend);
                        } else {
                            removeSelectedFriend(selected.friend.cust_id);
                            selectedMembers.remove(selected);
                        }

                        if (selectedMembers.size() < 1) {
                            rightTextView.setText(getResources().getString(
                                    R.string.sure));
                        } else {
                            rightTextView.setText(getResources().getString(
                                    R.string.sure)
                                    + "(" + selectedMembers.size() + ")");
                        }
                    }
                });
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                searchTextInUsers(s);
            }
        });
        choose_group_tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ActivityHandle.startActivity(ChooseContactsActivity.this,
                        MyGroupsActivity.class, null, -1);
            }
        });
    }

    @SuppressLint("DefaultLocale")
    private void searchTextInUsers(CharSequence text) {
        if (text != null && text.length() > 0) {
            if (TextUtils.isEmpty(text)) {
                return;
            }
            ArrayList<SelectedFriendEntity> tempMembers = new ArrayList<SelectedFriendEntity>();
            for (SelectedFriendEntity mFriendEntity : selectedFriendEntities) {
                String charIndex = mFriendEntity.friend.nick_name;
                if (mFriendEntity.friend.nick_name.toLowerCase(
                        Locale.getDefault()).contains(
                        text.toString().toLowerCase(Locale.getDefault()))
                        || charIndex.contains(text.toString().toLowerCase(
                        Locale.getDefault()))) {
                    tempMembers.add(mFriendEntity);
                }
            }
            if (tempMembers.size() > 0) {
                chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                        ChooseContactsActivity.this, tempMembers);
                pinnedListView.setAdapter(chooseGroupMemberAdapter);
            } else {
                pinnedListView.setVisibility(View.GONE);
            }
        } else {
            pinnedListView.setVisibility(View.VISIBLE);
            chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                    ChooseContactsActivity.this, selectedFriendEntities);
            pinnedListView.setAdapter(chooseGroupMemberAdapter);
        }
    }

    private void removeSelectedFriend(String cust_id) {
        int pos = -1;
        for (SelectedFriendEntity friend : selectedMembers) {
            pos++;
            if (friend.friend.cust_id.equals(cust_id)) {
                break;
            }
        }

        if (pos > -1) {
            if (selectedUserLayout != null) {
                selectedUserLayout.removeViewAt(pos);
            }
            scrollToEnd();
        }
    }

    private void addSelectedFriend(FriendEntity friend) {
        MaskImageView image = new MaskImageView(ChooseContactsActivity.this);

        LayoutParams lp = new LayoutParams(
                QyxWeightDensityUtils.dp2px(this, 35),
                QyxWeightDensityUtils.dp2px(this, 35));
        lp.setMargins(5, 0, 5, 0);
        image.setLayoutParams(lp);
        image.SetUrl(APIConfiguration.getAvatarUrlNormal(friend.cust_id,
                PacketType.PERSONAL));
        selectedUserLayout.addView(image);
        scrollToEnd();
    }

    public void scrollToEnd() {
        mHorizontalScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHorizontalScrollView
                        .fullScroll(HorizontalScrollView.FOCUS_RIGHT);
            }
        }, 100);
    }

    private void refresh() {
        QYXIMConfiguration.singleThreadExecutor.execute(new Runnable() {

            @Override
            public void run() {
                friends = FriendDB.getFriends();
                for (int i = 0, size = friends.size(); i < size; i++) {
                    SelectedFriendEntity selectedFriendEntity = new SelectedFriendEntity(
                            friends.get(i));
                    if (friend != null
                            && friend.cust_id.equals(friends.get(i).cust_id)) {
                        selectedFriendEntity.selectedStatus = 3;
                    } else if (isAddLabel) {
                        if (arraylist != null && arraylist.size() > 0) {
                            for (int j = 0, lenght = arraylist.size(); j < lenght; j++) {
                                if (arraylist.get(j) == null) {
                                    continue;
                                }
                                if (arraylist.get(j).cust_id != null
                                        && arraylist.get(j).cust_id
                                        .equals(friends.get(i).cust_id)) {
                                    selectedFriendEntity.selectedStatus = 3;
                                }
                            }
                        }
                    }
                    selectedFriendEntities.add(selectedFriendEntity);
                }
                myHandler.sendEmptyMessage(1);
            }
        });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message arg0) {
            if (arg0.what == 1) {
                if (isChooseCrad) {
                    FriendEntity friendEntity = new FriendEntity();
                    friendEntity.cust_id = IMApplication.getCustId();
                    friendEntity.nick_name = IMApplication.config
                            .getUserName();
                    selectedFriendEntities.add(0, new SelectedFriendEntity(
                            friendEntity));
                }
                chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                        ChooseContactsActivity.this, selectedFriendEntities);
                pinnedListView.setAdapter(chooseGroupMemberAdapter);
            }
            return false;
        }
    });

    private void labelChooseMembers() {
        Intent intent = new Intent(ChooseContactsActivity.this,
                CreateLabelActivity.class);
        ArrayList<FriendEntity> _arrayList = new ArrayList<FriendEntity>();
        for (int i = 0, size = selectedMembers.size(); i < size; i++) {
            _arrayList.add(selectedMembers.get(i).friend);
        }
        intent.putExtra("labelMembers", _arrayList);
        if (isAddLabel && arraylist != null && arraylist.size() > 0) {
            setResult(RESULT_OK, intent);
        } else {
            startActivity(intent);
        }
        finish();
    }
}
